// BoLe HR Platform - HR功能管理

class HRManager {
    constructor() {
        this.currentTab = 'stats';
        this.jobs = [];
        this.candidates = [];
        this.applications = [];
    }

    init() {
        // 演示模式下移除认证检查
        // 加载初始数据
        this.loadStats();
        this.bindEvents();
    }

    bindEvents() {
        // 搜索候选人
        const candidateSearch = document.getElementById('candidateSearch');
        if (candidateSearch) {
            candidateSearch.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchCandidates();
                }
            });
        }
    }

    async loadStats() {
        try {
            const stats = await api.getRecruitmentStats();
            this.updateStatsDisplay(stats);
        } catch (error) {
            console.error('Failed to load stats:', error);
            showToast('加载统计数据失败', 'error');
        }
    }

    updateStatsDisplay(stats) {
        document.getElementById('totalApplications').textContent = stats.total_applications || 0;
        document.getElementById('pendingReviews').textContent = stats.pending_reviews || 0;
        document.getElementById('interviewsScheduled').textContent = stats.interviews_scheduled || 0;
        document.getElementById('offersMade').textContent = stats.offers_made || 0;
    }

    async loadJobs() {
        const jobsList = document.getElementById('jobsList');
        showLoading(jobsList);

        try {
            const jobs = await api.getCompanyJobs();
            this.jobs = jobs;
            this.renderJobsList(jobs);
        } catch (error) {
            console.error('Failed to load jobs:', error);
            showError(jobsList, '加载职位失败');
        }
    }

    async loadCandidates() {
        const candidatesList = document.getElementById('candidatesList');
        if (!candidatesList) {
            console.error('❌ 找不到候选人列表容器');
            return;
        }

        showLoading(candidatesList);

        try {
            console.log('🔄 正在加载候选人数据...');
            const response = await api.getCandidates({
                skip: 0,
                limit: 20
            });
            
            console.log('📡 API响应:', response);
            const candidates = response.data || response;
            this.candidates = candidates;
            this.renderCandidatesList(candidates);
            
            console.log('✅ 候选人数据加载成功，共', candidates?.length || 0, '个候选人');
        } catch (error) {
            console.error('❌ 加载候选人失败:', error);
            showError(candidatesList, '加载候选人失败，请检查网络连接');
        }
    }

    renderJobsList(jobs) {
        const jobsList = document.getElementById('jobsList');
        
        if (jobs.length === 0) {
            showEmpty(jobsList, '暂无职位，点击创建职位开始招聘');
            return;
        }

        jobsList.innerHTML = jobs.map(job => `
            <div class="list-item">
                <div class="item-header">
                    <h4 class="item-title">${job.title}</h4>
                    <div class="item-actions">
                        <button class="btn btn-sm btn-outline" onclick="hrManager.editJob(${job.id})">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="hrManager.viewJobApplications(${job.id})">
                            <i class="fas fa-users"></i> 申请
                        </button>
                    </div>
                </div>
                <div class="item-meta">
                    <span class="meta-item">
                        <i class="fas fa-map-marker-alt"></i>
                        ${job.location || '未指定'}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-briefcase"></i>
                        ${job.experience_level}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-clock"></i>
                        ${formatDate(job.created_at)}
                    </span>
                    <span class="status-badge status-${job.is_active ? 'hired' : 'rejected'}">
                        ${job.is_active ? '招聘中' : '已关闭'}
                    </span>
                </div>
                <div class="item-content">
                    <p>${job.description.substring(0, 200)}${job.description.length > 200 ? '...' : ''}</p>
                    <div class="job-requirements">
                        <strong>技能要求：</strong>
                        ${job.requirements.map(req => `<span class="skill-tag">${req}</span>`).join('')}
                    </div>
                </div>
            </div>
        `).join('');
    }

    async searchCandidates() {
        const searchQuery = document.getElementById('candidateSearch').value.trim();
        if (!searchQuery) {
            showToast('请输入搜索关键词', 'warning');
            return;
        }

        const candidatesList = document.getElementById('candidatesList');
        showLoading(candidatesList);

        try {
            const searchData = {
                skills: searchQuery.split(',').map(s => s.trim()).filter(s => s),
                limit: 20
            };

            const candidates = await api.searchCandidates(searchData);
            this.candidates = candidates;
            this.renderCandidatesList(candidates);
        } catch (error) {
            console.error('Failed to search candidates:', error);
            showError(candidatesList, '搜索候选人失败');
        }
    }

    renderCandidatesList(candidates) {
        const candidatesList = document.getElementById('candidatesList');
        
        if (!candidates || candidates.length === 0) {
            showEmpty(candidatesList, '暂无候选人数据');
            return;
        }

        candidatesList.innerHTML = candidates.map(candidate => {
            // 兼容不同的数据结构
            const candidateData = candidate.candidate || candidate;
            return `
                <div class="list-item">
                    <div class="item-header">
                        <h4 class="item-title">${candidateData.name || candidateData.full_name || '未知姓名'}</h4>
                        <div class="item-actions">
                            <button class="btn btn-sm btn-outline" onclick="hrManager.viewCandidateDetails(${candidate.id})">
                                <i class="fas fa-eye"></i> 查看
                            </button>
                            <button class="btn btn-sm btn-primary" onclick="hrManager.analyzeCandidate(${candidate.id})">
                                <i class="fas fa-brain"></i> 分析
                            </button>
                        </div>
                    </div>
                    <div class="item-meta">
                        <span class="meta-item">
                            <i class="fas fa-map-marker-alt"></i>
                            ${candidate.location || '未指定'}
                        </span>
                        <span class="meta-item">
                            <i class="fas fa-briefcase"></i>
                            ${candidate.experience_years || 0}年经验
                        </span>
                        <span class="meta-item">
                            <i class="fas fa-star"></i>
                            匹配度: ${Math.round(item.match_score * 100)}%
                        </span>
                    </div>
                    <div class="item-content">
                        <p><strong>当前职位：</strong>${candidate.current_position || '未填写'}</p>
                        <div class="candidate-skills">
                            <strong>技能：</strong>
                            ${candidate.skills.map(skill => `<span class="skill-tag">${skill}</span>`).join('')}
                        </div>
                        <div class="match-info">
                            <div class="matching-skills">
                                <strong>匹配技能：</strong>
                                ${item.matching_skills.map(skill => `<span class="skill-tag skill-match">${skill}</span>`).join('')}
                            </div>
                            ${item.missing_skills.length > 0 ? `
                                <div class="missing-skills">
                                    <strong>缺少技能：</strong>
                                    ${item.missing_skills.map(skill => `<span class="skill-tag skill-missing">${skill}</span>`).join('')}
                                </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }

    async loadApplications() {
        const applicationsList = document.getElementById('applicationsList');
        showLoading(applicationsList);

        try {
            const applications = await api.getJobApplications();
            this.applications = applications;
            this.renderApplicationsList(applications);
        } catch (error) {
            console.error('Failed to load applications:', error);
            showError(applicationsList, '加载申请失败');
        }
    }

    renderApplicationsList(applications) {
        const applicationsList = document.getElementById('applicationsList');
        
        if (applications.length === 0) {
            showEmpty(applicationsList, '暂无申请');
            return;
        }

        applicationsList.innerHTML = applications.map(app => `
            <div class="list-item">
                <div class="item-header">
                    <div>
                        <h4 class="item-title">${app.candidate_name}</h4>
                        <p class="item-subtitle">${app.job_title}</p>
                    </div>
                    <div class="item-actions">
                        <select class="status-select" onchange="hrManager.updateApplicationStatus(${app.id}, this.value)">
                            <option value="pending" ${app.status === 'pending' ? 'selected' : ''}>待审核</option>
                            <option value="screening" ${app.status === 'screening' ? 'selected' : ''}>筛选中</option>
                            <option value="interview" ${app.status === 'interview' ? 'selected' : ''}>面试</option>
                            <option value="hired" ${app.status === 'hired' ? 'selected' : ''}>录取</option>
                            <option value="rejected" ${app.status === 'rejected' ? 'selected' : ''}>拒绝</option>
                        </select>
                        <button class="btn btn-sm btn-primary" onclick="hrManager.viewResume(${app.resume_id})">
                            <i class="fas fa-file-alt"></i> 简历
                        </button>
                    </div>
                </div>
                <div class="item-meta">
                    <span class="meta-item">
                        <i class="fas fa-calendar"></i>
                        ${formatDate(app.applied_at)}
                    </span>
                    ${app.match_score ? `
                        <span class="meta-item">
                            <i class="fas fa-star"></i>
                            匹配度: ${Math.round(app.match_score * 100)}%
                        </span>
                    ` : ''}
                    <span class="status-badge status-${app.status}">
                        ${this.getStatusText(app.status)}
                    </span>
                </div>
            </div>
        `).join('');
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '待审核',
            'screening': '筛选中',
            'interview': '面试',
            'hired': '录取',
            'rejected': '拒绝'
        };
        return statusMap[status] || status;
    }

    async updateApplicationStatus(applicationId, newStatus) {
        try {
            await api.updateApplicationStatus(applicationId, {
                status: newStatus
            });
            showToast('状态更新成功', 'success');
        } catch (error) {
            console.error('Failed to update application status:', error);
            showToast('状态更新失败', 'error');
        }
    }

    showCreateJobModal() {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-plus"></i> 创建新职位</h3>
            <form id="createJobForm">
                <div class="form-group">
                    <label for="jobTitle">职位名称</label>
                    <input type="text" id="jobTitle" name="title" required>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="jobLocation">工作地点</label>
                        <input type="text" id="jobLocation" name="location">
                    </div>
                    <div class="form-group">
                        <label for="jobExperience">经验要求</label>
                        <select id="jobExperience" name="experience_level" required>
                            <option value="entry">入门级</option>
                            <option value="mid">中级</option>
                            <option value="senior">高级</option>
                            <option value="lead">专家级</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="jobSalary">薪资范围</label>
                        <input type="text" id="jobSalary" name="salary_range" placeholder="如：15k-25k">
                    </div>
                    <div class="form-group">
                        <label for="jobType">工作类型</label>
                        <select id="jobType" name="employment_type">
                            <option value="full-time">全职</option>
                            <option value="part-time">兼职</option>
                            <option value="contract">合同</option>
                            <option value="internship">实习</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="jobRequirements">技能要求</label>
                    <input type="text" id="jobRequirements" name="requirements" 
                           placeholder="用逗号分隔，如：Python, React, SQL" required>
                </div>
                <div class="form-group">
                    <label for="jobDescription">职位描述</label>
                    <textarea id="jobDescription" name="description" rows="5" required></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 创建职位
                    </button>
                </div>
            </form>
        `;

        // 绑定表单提交事件
        document.getElementById('createJobForm').addEventListener('submit', (e) => this.handleCreateJob(e));
        
        showModal();
    }

    async handleCreateJob(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        
        const requirements = formData.get('requirements').split(',').map(r => r.trim()).filter(r => r);
        
        const jobData = {
            title: formData.get('title'),
            description: formData.get('description'),
            requirements: requirements,
            experience_level: formData.get('experience_level'),
            salary_range: formData.get('salary_range'),
            location: formData.get('location'),
            employment_type: formData.get('employment_type')
        };

        try {
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 创建中...';
            submitBtn.disabled = true;

            await api.createJob(jobData);
            showToast('职位创建成功', 'success');
            closeModal();
            
            // 刷新职位列表
            if (this.currentTab === 'jobs') {
                this.loadJobs();
            }

        } catch (error) {
            console.error('Failed to create job:', error);
            showToast(error.message || '职位创建失败', 'error');
        } finally {
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-save"></i> 创建职位';
            submitBtn.disabled = false;
        }
    }

    showResumeAnalysis() {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-file-alt"></i> 简历分析</h3>
            <div class="upload-area">
                <input type="file" id="resumeFile" accept=".pdf,.doc,.docx" style="display: none;">
                <div class="upload-prompt" onclick="document.getElementById('resumeFile').click()">
                    <i class="fas fa-cloud-upload-alt fa-3x"></i>
                    <p>点击上传简历文件</p>
                    <small>支持 PDF, DOC, DOCX 格式</small>
                </div>
            </div>
            <div id="analysisResult" style="display: none;">
                <!-- 分析结果将显示在这里 -->
            </div>
        `;

        document.getElementById('resumeFile').addEventListener('change', (e) => this.handleResumeUpload(e));
        showModal();
    }

    async handleResumeUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        const uploadArea = document.querySelector('.upload-area');
        uploadArea.innerHTML = `
            <div class="loading">
                <i class="fas fa-spinner fa-spin fa-2x"></i>
                <p>正在分析简历...</p>
            </div>
        `;

        try {
            const formData = new FormData();
            formData.append('file', file);

            // 这里应该调用简历上传和分析API
            // const result = await api.uploadAndAnalyzeResume(formData);
            
            // 模拟分析结果
            setTimeout(() => {
                this.showAnalysisResult({
                    score: 85,
                    strengths: ['技术技能丰富', '项目经验充足', '学习能力强'],
                    weaknesses: ['沟通技能待加强', '缺少团队领导经验'],
                    recommendations: ['建议参加软技能培训', '可考虑担任项目负责人']
                });
            }, 2000);

        } catch (error) {
            console.error('Resume analysis failed:', error);
            uploadArea.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>分析失败，请重试</p>
                </div>
            `;
        }
    }

    showAnalysisResult(result) {
        const analysisResult = document.getElementById('analysisResult');
        analysisResult.style.display = 'block';
        analysisResult.innerHTML = `
            <div class="analysis-summary">
                <h4>分析结果</h4>
                <div class="score-display">
                    <div class="score-circle">
                        <span class="score-value">${result.score}</span>
                        <span class="score-label">综合评分</span>
                    </div>
                </div>
            </div>
            <div class="analysis-details">
                <div class="strengths">
                    <h5><i class="fas fa-thumbs-up"></i> 优势</h5>
                    <ul>
                        ${result.strengths.map(strength => `<li>${strength}</li>`).join('')}
                    </ul>
                </div>
                <div class="weaknesses">
                    <h5><i class="fas fa-exclamation-triangle"></i> 待改进</h5>
                    <ul>
                        ${result.weaknesses.map(weakness => `<li>${weakness}</li>`).join('')}
                    </ul>
                </div>
                <div class="recommendations">
                    <h5><i class="fas fa-lightbulb"></i> 建议</h5>
                    <ul>
                        ${result.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                    </ul>
                </div>
            </div>
        `;
    }
}

// HR标签页切换
function showHRTab(tabName, event) {
    // 演示模式下跳过认证检查
    if (!isDemoMode()) {
        if (!authManager.requireHR()) return;
    }
    
    // 更新标签状态
    document.querySelectorAll('.dashboard-nav .nav-btn').forEach(btn => btn.classList.remove('active'));
    if (event && event.target) {
        event.target.classList.add('active');
    } else {
        // 如果没有event对象，通过tabName查找按钮
        const targetBtn = document.querySelector(`.dashboard-nav .nav-btn[onclick*="${tabName}"]`);
        if (targetBtn) targetBtn.classList.add('active');
    }
    
    // 显示对应内容
    document.querySelectorAll('#hr-dashboard .tab-content').forEach(content => content.classList.remove('active'));
    const targetContent = document.getElementById(`hr-${tabName}`);
    if (targetContent) targetContent.classList.add('active');
    
    hrManager.currentTab = tabName;
    
    // 根据标签名加载对应数据
    if (window.hrManager) {
        hrManager.currentTab = tabName;
        
        switch(tabName) {
            case 'stats':
                hrManager.loadStats();
                break;
            case 'jobs':
                hrManager.loadJobs();
                break;
            case 'candidates':
                hrManager.loadCandidates();
                break;
            case 'analysis':
                // 分析页面不需要加载数据
                break;
        }
    }
}

// 检查是否为演示模式
function isDemoMode() {
    // 检查环境
    if (window.location.hostname === 'localhost' || 
        window.location.hostname === '127.0.0.1' || 
        window.location.hostname.includes('10.112.140.137') ||
        window.location.port === '3000') {
        return true;
    }
    
    // 检查用户数据
    const currentUser = localStorage.getItem('user') || localStorage.getItem('currentUser');
    if (currentUser) {
        try {
            const userData = JSON.parse(currentUser);
            return userData.is_demo || userData.is_test;
        } catch (e) {
            return true;
        }
    }
    return true; // 默认为演示模式
}

// 全局函数
function showCreateJobModal() {
    hrManager.showCreateJobModal();
}

function searchCandidates() {
    hrManager.searchCandidates();
}

function showResumeAnalysis() {
    hrManager.showResumeAnalysis();
}

function showCandidateComparison() {
    showToast('功能开发中...', 'info');
}

function showBackgroundCheck() {
    showToast('功能开发中...', 'info');
}

// 创建全局HR管理器实例
const hrManager = new HRManager();